import { LOGIN, LOGOUT, SET_USER_INFO, REFRESH_INFO } from 'Constants/userConstants';
import Api from 'Utils/api';
import * as routerActions from 'react-router-redux';

function login(userInfo) {
  return {
    type: LOGIN,
    userInfo,
  };
}

function logout() {
  sessionStorage.clear();
  return {
    type: LOGOUT,
  };
}

export function requestLogin() {
  return (dispatch) => {
    const api = new Api({
      method: 'POST',
      path: '/login/super',
      success: ((json) => {
        dispatch(login(json));
      }),
    });
    api.run();
  };
}

export function requestLogout() {
  const api = new Api({
    method: 'DELETE',
    path: '/own',
  });
  api.run();
  return (dispatch) => {
    dispatch(logout());
    dispatch(routerActions.replace('/login'));
  };
}
export function setUserInformation(info) {
  return {
    type: SET_USER_INFO,
    info
  };
}
export function setRefreshInformation(info) {
  return {
    type: REFRESH_INFO,
    info
  };
}

export function setUserInfo(info) {
  const permissionsObj = { permissions: info.permission_ids };
  sessionStorage.setItem('permissions', JSON.stringify(permissionsObj));
  sessionStorage.setItem('userId', info.id);
  sessionStorage.setItem('userSocketAuth', info.socket_auth);
  sessionStorage.setItem('username', info.username);

  return (dispatch) => {
    const userInfo = {
      userId: info.id,
      userSocketAuth: info.socket_auth,
      username: info.username,
      nickname: info.nickname,
      permissions: info.permission_ids,
    };
    dispatch(setUserInformation(userInfo));
  };
}

export function setRefreshInfo(info) {
  const permissionsObj = { permissions: info.permission_ids };
  sessionStorage.setItem('permissions', JSON.stringify(permissionsObj));
  sessionStorage.setItem('userId', info.id);
  sessionStorage.setItem('userSocketAuth', info.socket_auth);
  sessionStorage.setItem('username', info.username);
  return (dispatch) => {
    const userInfo = {
      userId: info.id,
      nickname: info.nickname,
      permissions: info.permission_ids,
    };
    dispatch(setRefreshInformation(userInfo));
  };
}
